package com.yumo.kangchenjunga.company;

import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yumo.kangchenjunga.security.CustomUserDetails;

@Controller
@RequestMapping("")
public class CompanyPageController {

	@Autowired
	private CompanyService service;

	@GetMapping("/admin/companies")
	public String company(Model model, HttpServletRequest request,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		CompanyVo company = new CompanyVo();
		company.name = request.getParameter("name");
		company.category = Optional.ofNullable(StringUtils.trimToNull(request.getParameter("categoryId")))
				.map(Integer::valueOf).map(it -> new CompanyCategoryVo(it, null, null)).orElse(null);
		company.contacts = request.getParameter("contacts");
		company.phone = request.getParameter("phone");
		model.addAttribute("companies", service.query(company, pageable));
		model.addAttribute("categories", service.listCategory());
		model.addAttribute("search", company);
		return "admin/company";
	}

	@GetMapping("/admin/company/categories")
	public String companyCategory(Model model,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		model.addAttribute("categories", service.pageCategory(pageable));
		return "admin/company_category";
	}

	@GetMapping("/company/stores")
	public String store(Model model, HttpServletRequest request,
			@AuthenticationPrincipal CustomUserDetails currentUser,
			@PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.DESC) Pageable pageable) {
		StoreVo store = new StoreVo();
		store.name = request.getParameter("name");
		store.companyId = currentUser.getCompanyId();
		model.addAttribute("companies", service.list());
		model.addAttribute("stores", service.queryStores(store, pageable));
		model.addAttribute("search", store);
		return "company/store";
	}

}
